package cc.rengu.redp.flowable.delegate;

import cc.rengu.redp.flowable.bizmodel.BizModelBuilder;
import cc.rengu.redp.flowable.domain.FlowData;
import cc.rengu.redp.flowable.service.FlowDataService;
import cc.rengu.redp.flowable.service.impl.BizWorkFlowVar;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用于流程结束时，调用业务模型构建引擎实现业务数据构建
 *
 * @Author xushitang
 */
@Slf4j
@Service
public class EndEventForBuildBizModelDelegate implements JavaDelegate {
    @Autowired
    private BizModelBuilder bizModelBuilder;
    @Autowired
    private FlowDataService flowDataService;

    @Override
    public void execute(DelegateExecution execution) {
        //获取flowData
        FlowData flowData = flowDataService.getFlowData(execution.getProcessInstanceId());
        if (flowData == null) {
            //空再从变量里拿，减少读表次数
            BizWorkFlowVar currVar = new BizWorkFlowVar(execution.getVariables());
            flowData = flowDataService.getById(Long.valueOf(currVar.getFlowDataId()));
        }
        //构建BizModelData
        bizModelBuilder.trigToBuild(flowData.getFlowData(),
                execution.getProcessDefinitionId().split(":")[0],
                execution.getCurrentActivityId());
    }
}
